package com.gxuwz.endrskyweather.apiclient;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CheckUpdateClient {
    private static final String TAG = "CheckUpdateClient";
    private static final String VERSION_URL = "http://23.224.49.35:6555/version";
    private static final String UPDATES_URL = "http://23.224.49.35:6555/updates";

    private OkHttpClient client;

    public CheckUpdateClient() {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    public String checkVersion() throws IOException, JSONException {
        Request request = new Request.Builder().url(VERSION_URL).build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            String responseBodyString = response.body().string();
            Log.d(TAG, "checkVersion response version: " + responseBodyString);
            // 使用 gson 解析 json 获取版本号
            JSONObject json = new JSONObject(responseBodyString);
            return json.getString("version");
        }
    }


    public void downloadUpdates(Context context, String version) throws IOException {
        Log.d(TAG, "开始下载新版本APP");
        // 创建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "update_channel")
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setContentTitle("RSky Weather APP 更新")
                .setContentText("正在下载新版本，下载完毕后将自动跳转安装界面...")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(1, builder.build());

        // 设置下载请求
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(UPDATES_URL + "/endrskyweather_" + version + ".apk"))
                .setTitle("RSky Weather APP 更新")
                .setDescription("正在下载最新版本：v" + version)
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "endrskyweather_" + version + ".apk");

        // 获取下载服务并开始下载
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long downloadId = downloadManager.enqueue(request);

        // 监听下载完成
        new Thread(() -> {
            boolean downloading = true;
            while (downloading) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                android.database.Cursor cursor = downloadManager.query(query);
                if (cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        downloading = false;
                        // 下载完成，显示通知和Toast
                        builder.setContentText("下载完成，点击安装")
                               .setSmallIcon(android.R.drawable.stat_sys_download_done);
                        notificationManager.notify(1, builder.build());
                        
                        // 在主线程显示Toast
                        ((android.app.Activity) context).runOnUiThread(() -> {
                            Toast.makeText(context, "下载完成，准备安装", Toast.LENGTH_SHORT).show();
                            
                            // 获取下载文件的URI
                            Uri apkUri = downloadManager.getUriForDownloadedFile(downloadId);
                            if (apkUri != null) {
                                // 启动安装
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(install);
                            }
                        });
                    } else if (status == DownloadManager.STATUS_FAILED) {
                        downloading = false;
                        // 下载失败
                        builder.setContentText("下载失败")
                               .setSmallIcon(android.R.drawable.stat_notify_error);
                        notificationManager.notify(1, builder.build());
                        
                        ((android.app.Activity) context).runOnUiThread(() -> {
                            Toast.makeText(context, "下载失败，请重试", Toast.LENGTH_SHORT).show();
                        });
                    }
                }
                cursor.close();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.e(TAG, "downloadUpdates interrupted", e);
                }
            }
        }).start();
    }

}
